package openglsuperbible.Chapter7;

import de.matthiasmann.twl.utils.PNGDecoder;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import openglsuperbible.glutils.*;
import org.lwjgl.BufferUtils;
import org.lwjgl.LWJGLException;
import org.lwjgl.Sys;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL13.*;
import static org.lwjgl.opengl.GL12.*;
import static org.lwjgl.opengl.GL30.*;

/**
 *
 * @author Matthew
 */
public class NormalMapped {
        public static final int DISPLAY_HEIGHT = 600;
        public static final int DISPLAY_WIDTH = 800;

        public long lastFrame;
       
        private Shader normalMapShader;
        private MatrixStack modelViewMatrix;  // Modelview Matrix
        private MatrixStack projectionMatrix; // Projection Matrix
        private GLFrustrum frustrum;    // View Frustum
        private GeometryTransform transformPipeline; // Geometry Transform Pipeline
        private GLFrame cameraFrame;
        private GLBatch sphere;
        private int[] texture;
        private float angle = 0.0f;
        private float vEyeLight[] = { -100.0f, 100.0f, 150.0f };
        private float vAmbientColor[] = { 0.2f, 0.2f, 0.2f, 1.0f };
        private float vDiffuseColor[] = { 1.0f, 1.0f, 1.0f, 1.0f};
        
        public void initGL()
        {
            // Black background
            glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
            normalMapShader = new Shader("NormalMapped","NormalMapped"); 

     	glEnable(GL_DEPTH_TEST);
	glEnable(GL_CULL_FACE);

            
            frustrum = new GLFrustrum();               
            modelViewMatrix = new MatrixStack();
            cameraFrame = new GLFrame();
            sphere = GLBatchFactory.makeSphere(1.0f, 52, 26); 
            
            texture = new int[2];

            glActiveTexture(GL_TEXTURE0);
            texture[0] =  loadTexture("IceMoon",GL_LINEAR_MIPMAP_LINEAR,GL_LINEAR,GL_CLAMP_TO_EDGE);
            glBindTexture(GL_TEXTURE_2D, texture[0]);
           
            glActiveTexture(GL_TEXTURE1);
            texture[1] =  loadTexture("IceMoonBump",GL_LINEAR_MIPMAP_LINEAR,GL_LINEAR,GL_REPEAT);
            glBindTexture(GL_TEXTURE_2D, texture[1]);
           
        }
        
              
       

    void render()
    {    
        angle += 0.005f * getDelta();	
	// Clear the window with current clearing color
	 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

         float[] mCamera = cameraFrame.getCameraMatrix();
 
         modelViewMatrix.push();
            modelViewMatrix.multiply4(mCamera);

            modelViewMatrix.translate(0, 0, -5.0f);
            modelViewMatrix.rotate(-90.0f, 1.0f, 0.0f, 0.0f);
            modelViewMatrix.rotate(angle, 0, 0, 1);

            normalMapShader.use();
            normalMapShader.setUniform4("ambientColor", vAmbientColor);
            normalMapShader.setUniform4("diffuseColor", vDiffuseColor);
            normalMapShader.setUniform3("vLightPosition", vEyeLight);
            normalMapShader.setUniform1i("colorMap", 0);
            normalMapShader.setUniform1i("normalMap", 1);
            normalMapShader.setUniformMatrix4("mvpMatrix", transformPipeline.getModelViewProjectionMatrix()); 
            normalMapShader.setUniformMatrix4("mvMatrix",  transformPipeline.getModelViewMatrix());
            normalMapShader.setUniformMatrix3("normalMatrix",transformPipeline.getNormalMatrix());
     
            sphere.draw(normalMapShader.getAttributeLocations());     
        modelViewMatrix.pop();

	// Flush drawing commands
	Display.update();  
    }
 
    
    
       public void create() throws LWJGLException { 
            //Display    
            Display.setDisplayModeAndFullscreen(new DisplayMode(DISPLAY_WIDTH,DISPLAY_HEIGHT)); 
            
            Display.setTitle("normalMap");
            Display.create();
            
            //Keyboard         
            Keyboard.create();   
            //Mouse          
            Mouse.setGrabbed(false);
            Mouse.create();  
            //OpenGL      
            initGL();    
            resizeGL();  
        }  
       
        public void resizeGL() {   
            glViewport(0,0,DISPLAY_WIDTH ,DISPLAY_HEIGHT);
            frustrum.setPerspective(35f, Display.getWidth()/ Display.getHeight(),1.0f, 1000.0f);
            projectionMatrix = new MatrixStack(frustrum.getProjectionMatrix());
            // Set the transformation pipeline to use the two matrix stacks 
            transformPipeline = new GeometryTransform(modelViewMatrix, projectionMatrix);
        } 
       
            public void destroy() {  
                //Methods already check if created before destroying.  
                Mouse.destroy();   
                Keyboard.destroy();
                Display.destroy();     
            } 
        
            public static void main(String[] args) {
            NormalMapped main = null;
            try { 
                 main = new NormalMapped(); 
                main.create(); 
                main.run();
            }          
            catch(Exception ex) {  
                 
            }          
            finally { 
                if(main != null) {  
                    main.destroy();
                }         
            }      
        } 
            
            public void run() 
            {
                while (!Display.isCloseRequested() && !Keyboard.isKeyDown(Keyboard.KEY_ESCAPE)) {              
                
        
                render();
       
             
                Display.sync(60);
                Display.setVSyncEnabled(true); 
                
                }
            }
                        
                            	/** 
	 * Calculate how many milliseconds have passed 
	 * since last frame.
	 * 
	 * @return milliseconds passed since last frame 
	 */
	public int getDelta() {
	    long time = getTime();
	    int delta = (int) (time - lastFrame);
	    lastFrame = time;
	 
	    return delta;
	}
	
	/**
	 * Get the accurate system time
	 * 
	 * @return The system time in milliseconds
	 */
	public long getTime() {
	    return (Sys.getTime() * 1000) / Sys.getTimerResolution();
	}
        
               private int loadTexture(String filename, int minFilter, int magFilter, int wrapMode){
            
            InputStream in;
            int texID = glGenTextures();
            try {
                in = new FileInputStream("textures/" + filename + ".png");
                PNGDecoder decoder = new PNGDecoder(in);
                int width = decoder.getWidth();
                int height = decoder.getHeight();
                
                ByteBuffer buffer = BufferUtils.createByteBuffer(4 * width * height);
                decoder.decode(buffer, width * 4, PNGDecoder.Format.RGBA);          
                buffer.flip();
                in.close();
                
                glBindTexture(GL_TEXTURE_2D, texID);
                glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapMode);
                glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapMode);
                
                glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minFilter);
                glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magFilter);
                
                glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
                glTexImage2D(GL_TEXTURE_2D, 0,GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer);

//                             
                if(minFilter == GL_LINEAR_MIPMAP_LINEAR || 
                    minFilter == GL_LINEAR_MIPMAP_NEAREST ||
                     minFilter == GL_NEAREST_MIPMAP_LINEAR ||
                     minFilter == GL_NEAREST_MIPMAP_NEAREST){
                glGenerateMipmap(GL_TEXTURE_2D);}       
                glBindTexture(GL_TEXTURE_2D, 0);
                
            } catch (FileNotFoundException e) {
                System.err.println("Failed to find the texture file: " + filename + ".png");
                
            } catch (IOException ex) {
                System.err.println("Error reading file: " + filename + ".png");
                
            } 
           
            return texID;
        }
        
}
